package com.wan.word;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.umeng.analytics.MobclickAgent;
import com.wan.tool.HttpUtils;
import com.wan.tool.InAndOut;
import com.wan.tool.Word;

import java.io.File;
import java.io.IOException;

import cn.domob.android.ads.DomobAdView;


/**
 * Created by wan on 14-2-6.
 * 为了快速开发，单独创建一个activity，来解决actionbar＋sldingmenu 的时候overlay无效的问题
 */
public class ShowWordActivity extends SherlockActivity {

    private Handler handler = new Handler();

    private int delay = 3000;   //3s换下一个单词
    private boolean pause = false;  //默认不暂停
    private long lastHidingTime = 0l; //最后一次点击页面的时间
    private InAndOut.TaskInfo taskInfo;

    private boolean thisActivityDestory = false;

    private boolean wifi_fayin_tupian = true;

    //广告
    RelativeLayout mAdContainer;
    DomobAdView mAdview320x50;
    public static final String PUBLISHER_ID = "56OJzlS4uMnSLVtCGO";
    public static final String P_ID = "16TLm00lAceakY27DfO-vj4i";


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        setContentView(R.layout.word_showword);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        InAndOut.init(getSharedPreferences("word07", MODE_PRIVATE));

        //控制器初始化
        controlInit();

        //单词初始化
        showWordInit();

        mAdContainer = (RelativeLayout) findViewById(R.id.adcontainer);
        // 创建一个320x50的广告View
        mAdview320x50 = new DomobAdView(this, PUBLISHER_ID, P_ID, DomobAdView.INLINE_SIZE_320X50);
        mAdContainer.addView(mAdview320x50);
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        getSupportActionBar().show();
        findViewById(R.id.showword_control_layout).setVisibility(View.VISIBLE);
        hideActionBarDelayed(handler);
    }

    private void hideActionBarDelayed(Handler handler) {
        handler.postDelayed(new Runnable() {
            public void run() {
                if (!pause && System.currentTimeMillis() - lastHidingTime > 2900) {
                    getSupportActionBar().hide();
                    findViewById(R.id.showword_control_layout).setVisibility(View.INVISIBLE);
                    findViewById(R.id.home_control_status).setVisibility(View.VISIBLE);
                }
            }
        }, 3000);
    }

    public void controlInit() {
        pause = false;
        ((ToggleButton) findViewById(R.id.home_control_pause)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                pause = !b;
                if (!pause) {
                    hideActionBarDelayed(handler);
                }
            }
        });

        ((CheckBox) findViewById(R.id.home_controle_sound_pic)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    wifi_fayin_tupian = true;
                    mAdContainer.setVisibility(View.VISIBLE);
                } else {
                    wifi_fayin_tupian = false;
                    mAdContainer.setVisibility(View.INVISIBLE);
                }
            }
        });


        findViewById(R.id.home_control_time).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (delay) {
                    case 3000:
                        delay = 4000;
                        ((Button) view).setText("4s");
                        break;
                    case 4000:
                        delay = 6000;
                        ((Button) view).setText("6s");
                        break;
                    case 6000:
                        delay = 10000;
                        ((Button) view).setText("10s");
                        break;
                    case 10000:
                        delay = 1000;
                        ((Button) view).setText("1s");
                        break;
                    case 1000:
                        delay = 2000;
                        ((Button) view).setText("2s");
                        break;
                    case 2000:
                        delay = 4000;
                        ((Button) view).setText("4s");
                        break;
                }
                Toast.makeText(view.getContext(), "间隔：" + delay / 1000 + "s", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showWordInit() {
        taskInfo = InAndOut.TaskInfo.getTaskInfo(0);
        //如果没有创建任务
        if (taskInfo == null) {
            findViewById(R.id.showword_noword_layout).setVisibility(View.VISIBLE);
            findViewById(R.id.showword_control_layout).setVisibility(View.GONE);
            findViewById(R.id.showword_noword).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    backHome();
                }
            });
        } else {
            findViewById(R.id.showword_noword_layout).setVisibility(View.GONE);
            findViewById(R.id.showword_control_layout).setVisibility(View.VISIBLE);
            findViewById(R.id.home_control_status).setVisibility(View.INVISIBLE);
            findViewById(R.id.showword_layout).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    getSupportActionBar().show();
                    findViewById(R.id.showword_control_layout).setVisibility(View.VISIBLE);
                    findViewById(R.id.home_control_status).setVisibility(View.INVISIBLE);
                    hideActionBarDelayed(handler);
                }
            });
            ((TextView) findViewById(R.id.home_control_task_name)).setText(taskInfo.taskName);
            //开始展示
            ((ToggleButton) findViewById(R.id.home_control_pause)).setChecked(true);
            beginToShowWord();

        }
    }

    private void beginToShowWord() {
        if (taskInfo == null) {
            //没有任务
            return;
        }
        if (taskInfo != null && taskInfo.wordList == null) {
            // 将数据库内容取出来
            taskInfo.loadWord();
        }

        //显示第一个单词
        startShowWord(0);
    }

    private void startShowWord(int delay) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                showNextWord();
            }
        }, delay);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backHome();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void backHome() {
        this.thisActivityDestory = true;
        this.finish();
    }

    private void showNextWord() {
        if (taskInfo == null) {
            //没有任务
            return;
        }
        if (thisActivityDestory) {
            return;
        }
        if (pause) {
            startShowWord(500);
        } else {
            if (taskInfo.wordList != null) {
                final TextView wordText = (TextView) findViewById(R.id.word_english);
                final TextView yinText = (TextView) findViewById(R.id.word_yin);
                final TextView chineseText = (TextView) findViewById(R.id.word_chinese);
                final ImageView imageView = (ImageView) findViewById(R.id.showword_netpic);
                imageView.setVisibility(View.INVISIBLE);
                wordText.setAlpha(0);
                yinText.setAlpha(0);
                chineseText.setAlpha(0);


                final Word word = taskInfo.nextWord();
                if (word == null) {
                    //结束了
                    backHome();
                } else {
                    if (word.yin == null) {
                        word.yin = "";
                    } else {
                        word.yin = word.yin.replace("#", " ");
                    }
                    wordText.setText(word.word);
                    yinText.setText(word.yin);
                    chineseText.setText(word.chinese);
                    //0.2s 出英文＋音标  1.8s后出汉语
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            wordText.setAlpha(1f);
                            yinText.setAlpha(1f);
                            if (wifi_fayin_tupian) {
                                if (new File(HttpUtils.getSoundPath(word.num)).exists()) {
                                    MediaPlayer mediaPlayer = new MediaPlayer();
                                    try {
                                        mediaPlayer.setDataSource(HttpUtils.getSoundPath(word.num));
                                        mediaPlayer.prepare();
                                        mediaPlayer.start();
                                        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                            @Override
                                            public void onCompletion(MediaPlayer m) {
                                                m.release();
                                            }
                                        });

                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }, 200);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            chineseText.setAlpha(1f);
                            if (new File(HttpUtils.getPicPath(word.num)).exists()) {

                                Bitmap myBitmap = BitmapFactory.decodeFile(HttpUtils.getPicPath(word.num));
                                imageView.setImageBitmap(myBitmap);
                                imageView.setVisibility(View.VISIBLE);
                            }
                            word.showStatus = 1;
                        }
                    }, 600);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            word.showStatus = 2;
                        }
                    }, delay + 1500);
                    String status = taskInfo.nowIndex + "/" + taskInfo.wordList.size();
                    ((TextView) findViewById(R.id.home_control_status)).setText(status);
                    startShowWord(delay + 1500);
                    Word nowWord = taskInfo.olnyGetNowWord();
                    if (nowWord != null) {
                        if (wifi_fayin_tupian) {
                            if (HttpUtils.isWifiConnect(this)) {
                                HttpUtils.downOneWord(nowWord.num);
                            }
                        }
                    }
                }
            }
        }
    }


    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.backHome();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        //将线程销毁掉
        thisActivityDestory = true;
        super.onDestroy();
    }

}
